import os
import sys
from pathlib import Path

from openai import OpenAI

from ag.model import get_model
from ag.io import stderr


class Config:
    def __init__(self, args):
        self.client = None
        self.model = get_model(args.model)
        self.check_client()
        if self.model is None:
            stderr(f"不支持的模型: {args.model}")
            sys.exit(1)
        self.json = args.json
        self.onetime = args.onetime
        self.remember = args.remember
        self.verbose = args.verbose
        self.interactive = args.interactive
        if self.json:
            self.onetime = True

        self.prompt = args.prefix if args.prefix is not None else ""

        if args.file:
            # 若输入文件，则将文件内容作为提示词（覆盖prompt）
            file = Path(args.file)
            if file.is_file():
                self.prompt += file.read_text()
        elif args.prompt:
            # 否则使用 prompt 给定的提示词，若为 interactive 模式，每条提示词之前默认加上该 prompt
            self.prompt += args.prompt
        else:
            if not args.interactive:
                self.prompt += sys.stdin.read()


    def check_client(self):
        try:
            self.client = OpenAI(
                api_key=os.getenv(self.model.apikey),
                base_url=self.model.url,
            )
        except Exception as e:
            stderr(str(e))
            sys.exit(1)

    def debug(self):
        stderr(f"模型名称: {self.model.name}")
        stderr("[结构化输出模式]" if self.json else "")
        stderr("[多轮对话模式]" if self.remember else "")
        stderr("[对话结果统计]" if self.verbose else "")
        stderr("[非流式输出]" if self.onetime else "")
